package com.dark.util;

import com.dark.base.FlowerFallingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * ClassName: DownloadUtil
 * Description:DownloadUtil
 *
 * @author chengluchao
 * @date: 2023/5/24 3:46 PM
 * @since 1.4.25
 */
@Slf4j
public class DownloadUtil {


    /**
     * 空对空的文件下载
     *
     * @param remoteFile 第三方url
     * @param name       文件名
     * @param response   响应
     * @throws IOException
     */
    public static void doExecuteTaskForRemoteFile(String remoteFile, String name, HttpServletResponse response) throws IOException {
        remoteFile = optimizationPath(remoteFile);
        String fileName = URLEncoder.encode(name, "utf-8");
        URL url = new URL(remoteFile);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(10000 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        InputStream ips = conn.getInputStream();
        String contentType = conn.getHeaderField("contentType");
        String contentLength = conn.getHeaderField("Content-Length");

        response.reset();
        response.setContentLength(org.springframework.util.StringUtils.isEmpty(contentLength) ? 9999 : Integer.parseInt(contentLength));
        response.setContentType(StringUtils.isEmpty(contentType) ? "application/octet-stream" : contentType);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName);
        OutputStream os = response.getOutputStream();

        try {
            byte[] buff = new byte[10240];
            int len;
            while ((len = ips.read(buff)) != -1) {
                os.write(buff, 0, len);
                os.flush();
            }
        } catch (IOException e) {
            log.error("文件下载异常", e);
            throw new FlowerFallingException("文件下载异常");
        }
    }

    /**
     * 优化路径
     *
     * @param remoteFilePath
     * @return
     */
    private static String optimizationPath(String remoteFilePath) {
        // 1. 京东JSS文件，换为内网地址
        if (remoteFilePath.startsWith("https://storage.jd.com")) {
            return remoteFilePath.replace("https://storage.jd.com", "http://storage.jd.local");
        }
        return remoteFilePath;
    }

}
